package com.bawei.module_mine.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.IIntent
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_mine.model.service.AddressService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

sealed class EditAddressIntent : IIntent {
    data class UpdateAddress(val params: Map<String, Any?>) : EditAddressIntent()
    data class DeleteAddress(val addressId: Long) : EditAddressIntent()
}

sealed class EditAddressState {
    object Init : EditAddressState()
    object Loading : EditAddressState()
    object UpdateSuccess : EditAddressState()
    object DeleteSuccess : EditAddressState()
    data class Failed(val msg: String) : EditAddressState()
}

class EditAddressViewModel : BaseViewModel<EditAddressIntent>() {
    private val _state = MutableStateFlow<EditAddressState>(EditAddressState.Init)
    val state: StateFlow<EditAddressState> get() = _state
    private val service by lazy { AddressService() }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    is EditAddressIntent.UpdateAddress -> updateAddress(intent.params)
                    is EditAddressIntent.DeleteAddress -> deleteAddress(intent.addressId)
                }
            }
        }
    }

    private fun updateAddress(params: Map<String, Any?>) {
        _state.value = EditAddressState.Loading
        viewModelScope.launch {
            try {
                val result = service.updateAddress(params)
                if (result.code == 200) {
                    _state.value = EditAddressState.UpdateSuccess
                } else {
                    _state.value = EditAddressState.Failed(result.msg ?: "更新失败")
                }
            } catch (e: Exception) {
                _state.value = EditAddressState.Failed(e.message ?: "网络异常")
            }
        }
    }

    private fun deleteAddress(addressId: Long) {
        _state.value = EditAddressState.Loading
        viewModelScope.launch {
            try {
                val result = service.deleteAddress(addressId)
                if (result.code == 200) {
                    _state.value = EditAddressState.DeleteSuccess
                } else {
                    _state.value = EditAddressState.Failed(result.msg ?: "删除失败")
                }
            } catch (e: Exception) {
                _state.value = EditAddressState.Failed(e.message ?: "网络异常")
            }
        }
    }
} 